#!/bin/sh
set -e
. /usr/share/debconf/confmodule

# Create new group for frepple
getent group frepple > /dev/null 2>&1 || addgroup --quiet frepple

# Remove execute permissions for non-members
chgrp frepple /usr/bin/frepple /usr/bin/frepplectl
chmod o= /usr/bin/frepple /usr/bin/frepplectl

# Add apache user to the frepple and monitoring groups
. /etc/apache2/envvars
adduser --quiet www-data frepple
adduser --quiet www-data adm

# Set permissions on configuration files
chgrp frepple /etc/frepple /etc/frepple/*
chmod 770 /etc/frepple
chmod 750 /etc/frepple/*

# Activate apache modules
a2enmod -q expires
a2ensite -q z_frepple
a2enmod -q http2
a2enmod -q proxy
a2enmod -q proxy_http
a2enmod -q proxy_wstunnel
a2enmod -q rewrite

# Wsgi file must be writeable to the group to allow reloading the app
chgrp frepple /usr/share/frepple/venv/lib/python*/site-packages/freppledb/wsgi.py
chmod 770 /usr/share/frepple/venv/lib/python*/site-packages/freppledb/wsgi.py

# Create log directory and set its permissions
if [ ! -d /var/log/frepple ]; then
  mkdir -p /var/log/frepple
  chgrp frepple /var/log/frepple
  chmod g=rwx,o= /var/log/frepple
fi

# Update secret key in the configuration file
sed -i "s/RANDOMSTRING/`date`/" /etc/frepple/djangosettings.py

# Offer to run migration during an upgrade
if [ "$1" = "configure" ] && [ -n "$2" ]; then
  db_get frepple/run_migration
  if [ "$RET" = true ]; then
      frepplectl migrate
  fi
fi

if [ "$1" = "configure" ]; then
  ldconfig
fi

exit 0
